import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Save, X, Plus, Trash2, AlertTriangle } from "lucide-react";

// 常量移至组件外部，避免每次渲染重新创建
const CATEGORYSTRUCTURE = {
  土石方工程施工: {
    name: "土石方工程施工",
    secondary: {
      路径复测: {
        name: "路径复测",
        tertiary: ["路径复测"],
      },
      basics: {
        name: "基础分坑和开挖",
        tertiary: ["基础分坑", "基坑开挖"],
      },
    },
  },
  线路防护设施施工: {
    name: "线路防护设施施工",
    secondary: {
      线路防护设施施工: {
        name: "线路防护设施施工",
        tertiary: ["线路防护设施施工"],
      },
    },
  },
  铁塔工程施工: {
    name: "铁塔工程施工",
    secondary: {
      铁塔工程施工: {
        name: "铁塔工程施工",
        tertiary: ["铁塔组立与拆除"],
      },
    },
  },
  试验工程: {
    name: "试验工程",
    secondary: {
      铁塔工程施工: {
        name: "电气试验",
        tertiary: ["线路绝缘、核相、参数测试"],
      },
    },
  },
  接地工程施工: {
    name: "接地工程施工",
    secondary: {
      铁塔工程施工: {
        name: "接地工程施工",
        tertiary: ["接地工程施工"],
      },
    },
  },
  架线工程施工: {
    name: "架线工程施工",
    secondary: {
      铁塔工程施工: {
        name: "导地线架设与拆除",
        tertiary: [
          "跨越架搭设与拆除",
          "封网架设与拆除",
          "架线与拆除导地线(含光缆)",
          "导地线压接",
          "紧线、附件安装(含光缆)",
        ],
      },
    },
  },
  基础施工: {
    name: "基础施工",
    secondary: {
      铁塔工程施工: {
        name: "现浇、角钢插入式铁塔、含承台、连梁、预制装配式、拉线基础施工",
        tertiary: ["钢筋制作与安装", "模板安装", "混凝土浇制", "拆模", ""],
      },
      人工挖孔桩掏挖基础施工: {
        name: "人工挖孔桩、掏挖基础施工",
        tertiary: ["钢筋制作与安装"],
      },
      灌注桩基础施工: {
        name: "灌注桩基础施工",
        tertiary: ["钢筋制作与安装"],
      },
      机械成孔灌注桩基础施工: {
        name: "机械成孔灌注桩基础施工",
        tertiary: ["钻孔"],
      },
      贯入桩基础施工: {
        name: "贯入桩基础施工",
        tertiary: ["贯入桩基础施工"],
      },
      水泥搅拌桩基础施工: {
        name: "水泥搅拌桩基础施工",
        tertiary: ["水泥搅拌桩基础施工"],
      },
    },
  },
  材料运输施工: {
    name: "材料运输施工",
    secondary: {
      材料运输: {
        name: "材料运输",
        tertiary: ["材料运输"],
      },
    },
  },
};

// const riskTypeS = [
//   { key: "poisoning", label: "中毒", description: "" },
//   { key: "suffocation", label: "窒息", description: "" },
//   { key: "tripFall", label: "摔绊", description: "" },
//   { key: "fall", label: "坠落", description: "" },
//   { key: "fallFromHeight", label: "高处坠落", description: "" },
//   { key: "struckByObject", label: "物体打击", description: "" },
//   { key: "strike", label: "打击", description: "" },
//   { key: "sprain", label: "扭伤", description: "" },
//   { key: "burn", label: "烧伤", description: "" },
//   { key: "burnFire", label: "烧伤（引起火灾）", description: "" },
//   { key: "scald", label: "灼伤", description: "" },
//   { key: "scaldBurn", label: "灼（烫）伤", description: "" },
//   { key: "electricShock", label: "触电", description: "" },
//   { key: "personalElectricShock", label: "人身触电", description: "" },
//   { key: "equipmentTrip", label: "设备跳闸", description: "" },
//   { key: "equipmentDamage", label: "设备损坏", description: "" },
//   { key: "equipmentBreakdown", label: "设备破损", description: "" },
//   { key: "equipmentShutdown", label: "设备停运", description: "" },
//   { key: "equipmentPowerOutage", label: "停电", description: "" },
//   { key: "equipmentBurn", label: "设备烧损", description: "" },
//   { key: "partialPowerOutage", label: "局部停电", description: "" },
//   { key: "fire", label: "火灾", description: "" },
//   { key: "explosion", label: "爆炸", description: "" },
//   { key: "collapse", label: "坍塌", description: "" },
//   { key: "landslide", label: "塌方", description: "" },
//   { key: "drowning", label: "溺水", description: "" },
//   { key: "drowningAlt", label: "淹溺", description: "" },
//   { key: "stab", label: "刺伤", description: "" },
//   { key: "cut", label: "割伤", description: "" },
//   { key: "clip", label: "夹伤", description: "" },
//   { key: "entanglement", label: "绞伤", description: "" },
//   { key: "mechanicalInjury", label: "机械伤害", description: "" },
//   { key: "lungDysfunction", label: "肺功能障碍", description: "" },
//   { key: "occupationalDisease", label: "职业病", description: "" },
//   { key: "crash", label: "碰撞", description: "" },
//   { key: "crushInjury", label: "压伤", description: "" },
//   { key: "socialResponsibility", label: "社会责任", description: "" },
//   { key: "personalCasualty", label: "人身伤亡", description: "" },
//   { key: "frameOverturn", label: "架体倾覆", description: "" },
//   { key: "trafficAccident", label: "交通意外", description: "" },
// ];
const riskTypeS = [
  { key: "poisoning", label: "中毒", description: "" },
  { key: "suffocation", label: "窒息", description: "" },
  { key: "tripFall", label: "摔绊", description: "" },
  { key: "fall", label: "坠落", description: "" },
  { key: "fallFromHeight", label: "高处坠落", description: "" },
  { key: "struckByObject", label: "物体打击", description: "" },
  { key: "strike", label: "打击", description: "" },
  { key: "sprain", label: "扭伤", description: "" },
  { key: "burn", label: "烧伤", description: "" },
  { key: "burnFire", label: "烧伤（引起火灾）", description: "" },
  { key: "scald", label: "灼伤", description: "" },
  { key: "scaldBurn", label: "灼（烫）伤", description: "" },
  { key: "electricShock", label: "触电", description: "" },
  { key: "personalElectricShock", label: "人身触电", description: "" },
  { key: "equipmentTrip", label: "设备跳闸", description: "" },
  { key: "equipmentDamage", label: "设备损坏", description: "" },
  { key: "equipmentBreakdown", label: "设备破损", description: "" },
  { key: "equipmentShutdown", label: "设备停运", description: "" },
  { key: "equipmentPowerOutage", label: "停电", description: "" },
  { key: "equipmentBurn", label: "设备烧损", description: "" },
  { key: "partialPowerOutage", label: "局部停电", description: "" },
  { key: "fire", label: "火灾", description: "" },
  { key: "explosion", label: "爆炸", description: "" },
  { key: "collapse", label: "坍塌", description: "" },
  { key: "landslide", label: "塌方", description: "" },
  { key: "drowning", label: "溺水", description: "" },
  { key: "drowningAlt", label: "淹溺", description: "" },
  { key: "stab", label: "刺伤", description: "" },
  { key: "cut", label: "割伤", description: "" },
  { key: "clip", label: "夹伤", description: "" },
  { key: "entanglement", label: "绞伤", description: "" },
  { key: "mechanicalInjury", label: "机械伤害", description: "" },
  { key: "lungDysfunction", label: "肺功能障碍", description: "" },
  { key: "occupationalDisease", label: "职业病", description: "" },
  { key: "crash", label: "碰撞", description: "" },
  { key: "crushInjury", label: "压伤", description: "" },
  { key: "socialResponsibility", label: "社会责任", description: "" },
  { key: "personalCasualty", label: "人身伤亡", description: "" },
  { key: "frameOverturn", label: "架体倾覆", description: "" },
  { key: "trafficAccident", label: "交通意外", description: "" },
];
const riskAssessmentSTANDARDS = {
  likelihood: {
    factorName: "可能性(L)",
    referenceScale: [
      {
        value: 10,
        label: "完全可以预料",
        description: "在现有防护措施下，危险的发生完全可以预料",
      },
      {
        value: 6,
        label: "相当可能",
        description: "在现有防护措施下，危险的发生相当可能",
      },
      {
        value: 3,
        label: "可能，但不经常",
        description: "在现有防护措施下，偶尔可能发生危险",
      },
      {
        value: 1,
        label: "可能性小，完全意外",
        description: "在现有防护措施下，危险发生的可能性小，属意外",
      },
      {
        value: 0.5,
        label: "很不可能，可以设想",
        description: "在现有防护措施下，危险发生的可能性很小，但可以设想",
      },
      {
        value: 0.2,
        label: "极不可能",
        description: "在现有防护措施下，危险发生的可能性极小，不易发生",
      },
      {
        value: 0.1,
        label: "实际不可能",
        description: "在现有防护措施下，危险发生的可能性极小，实际不可能发生",
      },
    ],
  },
  consequence: {
    factorName: "后果(C)",
    referenceScale: [
      {
        value: 100,
        label: "灾难",
        description:
          "造成10人以上死亡，或者50人以上100人以下重伤，或者5000万元以上1亿元以下直接经济损失的事故",
      },
      {
        value: 40,
        label: "大灾难",
        description:
          "造成3人以上10人以下死亡，或者10人以上50人以下重伤，或者1000万元以上5000万元以下直接经济损失的事故",
      },
      {
        value: 15,
        label: "严重",
        description:
          "造成1人以上3人以下死亡，或者10人以下重伤，或者100万元以上1000万元以下直接经济损失的事故",
      },
      {
        value: 7,
        label: "重要",
        description: "造成3人以下轻伤，或者100万元以下直接经济损失的事故",
      },
      {
        value: 3,
        label: "明显",
        description: "不会造成人员死亡、重伤，经济损失较小",
      },
      { value: 1, label: "轻微", description: "轻微擦伤、淤伤，不需要救护" },
    ],
  },
  exposure: {
    factorName: "暴露(E)",
    referenceScale: [
      {
        value: 10,
        label: "连续暴露",
        description: "每天工作期间，连续地暴露于潜在危险环境",
      },
      {
        value: 6,
        label: "每天工作时间内暴露",
        description: "每天工作时，约一次暴露于潜在危险环境",
      },
      {
        value: 3,
        label: "每周一次或偶然暴露",
        description: "每周一次，或每月数次暴露于潜在危险环境",
      },
      {
        value: 2,
        label: "每月一次暴露",
        description: "每月一次暴露于潜在危险环境",
      },
      {
        value: 1,
        label: "每年几次暴露",
        description: "每年几次暴露于潜在危险环境",
      },
      {
        value: 0.5,
        label: "很罕见地暴露",
        description: "非常罕见地暴露于潜在危险环境",
      },
    ],
  },
  riskLevels: [
    {
      name: "重大风险",
      min: 320,
      max: 400,
      color: "#dc2626",
      description: "必须立即采取措施",
    },
    {
      name: "较大风险",
      min: 160,
      max: 319,
      color: "#ea580c",
      description: "需要采取紧急措施",
    },
    {
      name: "一般风险",
      min: 70,
      max: 159,
      color: "#d97706",
      description: "需要注意",
    },
    {
      name: "低风险",
      min: 20,
      max: 69,
      color: "#2563eb",
      description: "或许可以接受",
    },
    {
      name: "可接受风险",
      min: 1,
      max: 19,
      color: "#16a34a",
      description: "可以接受",
    },
  ],
};

// 纯函数提取到组件外部
const calculateRiskLevel = (riskValue) => {
  for (const level of riskAssessmentSTANDARDS.riskLevels) {
    if (riskValue >= level.min && riskValue <= level.max) {
      return {
        name: level.name,
        color: level.color,
        description: level.description,
      };
    }
  }
  return { name: "V级(可接受风险)", color: "#16a34a", description: "可以接受" };
};

// 优化风险类型选项组件
const RiskTypeCheckbox = React.memo(({ type, checked, onCheckChange }) => (
  <div className="flex items-center space-x-2">
    <Checkbox id={type.key} checked={checked} onCheckedChange={onCheckChange} />
    <Label htmlFor={type.key} className="text-sm cursor-pointer">
      {type.label}
    </Label>
  </div>
));

// 优化控制措施输入组件
const ControlMeasureInput = React.memo(
  ({ measure, index, onMeasureChange, onRemove, canRemove }) => (
    <div key={index} className="flex items-center gap-2">
      <Input
        value={measure}
        onChange={(e) => onMeasureChange(index, e.target.value)}
        placeholder={`控制措施 ${index + 1}`}
        className="flex-1"
      />
      <Button
        type="button"
        variant="ghost"
        size="icon"
        onClick={() => onRemove(index)}
        disabled={!canRemove}
      >
        <Trash2 className="w-4 h-4 text-red-500" />
      </Button>
    </div>
  )
);

export default React.memo(function SafetyRiskPointForm({
  riskPoint,
  onSubmit,
  onCancel,
}) {
  const [formData, setFormData] = useState({
    riskCode: "",
    riskName: "",
    riskType: [],
    primaryCategory: "",
    secondaryCategory: "",
    tertiaryCategory: "",
    riskDescription: "",
    controlMeasures: [""],
    baseLikelihood: 1,
    baseConsequence: 1,
    baseExposure: 1,
    baseRiskValue: 1,
    baseRiskLevel: "V级(可接受风险)",
    applicableScope: "",
    id: "",
  });

  // 初始化数据处理
  useEffect(() => {
    if (!riskPoint && !formData.riskCode) {
      const timestamp = Date.now();
      const code = `SR-${timestamp}`;
      setFormData((prev) => ({ ...prev, riskCode: code }));
    } else if (riskPoint) {
      setFormData((prev) => ({
        ...prev,
        id: riskPoint.id || "",
        riskCode: riskPoint.riskCode || "",
        riskName: riskPoint.riskName || "",
        riskType: Array.isArray(riskPoint.riskType)
          ? [...riskPoint.riskType]
          : [],
        primaryCategory: riskPoint.primaryCategory || "",
        riskDescription: riskPoint.riskDescription || "",
        applicableScope: riskPoint.applicableScope || "",
        baseLikelihood: riskPoint.baseLikelihood || 1,
        baseConsequence: riskPoint.baseConsequence || 1,
        baseExposure: riskPoint.baseExposure || 1,
        baseRiskValue: riskPoint.baseRiskValue || 1,
        baseRiskLevel: riskPoint.baseRiskLevel || "V级(可接受风险)",
        controlMeasures:
          riskPoint.controlMeasures && riskPoint.controlMeasures.length
            ? [...riskPoint.controlMeasures]
            : [""],
      }));
    }
  }, [riskPoint]);

  // 处理二级分类
  useEffect(() => {
    if (riskPoint && formData.primaryCategory && riskPoint.secondaryCategory) {
      const isValid =
        CATEGORYSTRUCTURE[formData.primaryCategory]?.secondary?.[
          riskPoint.secondaryCategory
        ];
      if (isValid) {
        setFormData((prev) => ({
          ...prev,
          secondaryCategory: riskPoint.secondaryCategory,
        }));
      }
    }
  }, [formData.primaryCategory, riskPoint]);

  // 处理三级分类
  useEffect(() => {
    if (riskPoint && formData.secondaryCategory && riskPoint.tertiaryCategory) {
      const isValid = CATEGORYSTRUCTURE[formData.primaryCategory]?.secondary?.[
        formData.secondaryCategory
      ]?.tertiary?.includes(riskPoint.tertiaryCategory);
      if (isValid) {
        setFormData((prev) => ({
          ...prev,
          tertiaryCategory: riskPoint.tertiaryCategory,
        }));
      }
    }
  }, [formData.secondaryCategory, riskPoint, formData.primaryCategory]);

  // 计算风险值和等级 - 优化更新逻辑
  useEffect(() => {
    const calculate = () => {
      const likelihood = formData.baseLikelihood || 1;
      const consequence = formData.baseConsequence || 1;
      const exposure = formData.baseExposure || 1;
      const riskValue = likelihood * consequence * exposure;
      const riskLevel = calculateRiskLevel(riskValue);

      return { riskValue, riskLevel };
    };

    // 避免不必要的状态更新
    const { riskValue, riskLevel } = calculate();
    if (
      formData.baseRiskValue !== riskValue ||
      formData.baseRiskLevel !== riskLevel.name
    ) {
      setFormData((prev) => ({
        ...prev,
        baseRiskValue: riskValue,
        baseRiskLevel: riskLevel.name,
      }));
    }
  }, [
    formData.baseLikelihood,
    formData.baseConsequence,
    formData.baseExposure,
  ]);

  // 稳定的字段更新函数
  const handleFieldChange = useCallback((field, value) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }, []);

  // 控制措施更新函数
  const handleMeasureChange = useCallback((index, value) => {
    setFormData((prev) => {
      const newMeasures = [...prev.controlMeasures];
      newMeasures[index] = value;
      return { ...prev, controlMeasures: newMeasures };
    });
  }, []);

  // 添加控制措施
  const addMeasure = useCallback(() => {
    setFormData((prev) => ({
      ...prev,
      controlMeasures: [...prev.controlMeasures, ""],
    }));
  }, []);

  // 删除控制措施
  const removeMeasure = useCallback((index) => {
    setFormData((prev) => {
      if (prev.controlMeasures.length > 1) {
        const newMeasures = prev.controlMeasures.filter((_, i) => i !== index);
        return { ...prev, controlMeasures: newMeasures };
      }
      return prev;
    });
  }, []);

  // 提交处理
  const handleSubmit = useCallback(
    (e) => {
      e.preventDefault();
      const submitData = {
        ...formData,
        controlMeasures: formData.controlMeasures.filter(
          (m) => m.trim() !== ""
        ),
      };
      onSubmit(submitData);
    },
    [formData, onSubmit]
  );

  // 缓存分类选项计算结果
  const secondaryOptions = useMemo(() => {
    if (!formData.primaryCategory) return [];
    return Object.entries(
      CATEGORYSTRUCTURE[formData.primaryCategory]?.secondary || {}
    );
  }, [formData.primaryCategory]);

  const tertiaryOptions = useMemo(() => {
    if (!formData.primaryCategory || !formData.secondaryCategory) return [];
    return (
      CATEGORYSTRUCTURE[formData.primaryCategory]?.secondary[
        formData.secondaryCategory
      ]?.tertiary || []
    );
  }, [formData.primaryCategory, formData.secondaryCategory]);

  const currentRiskLevel = useMemo(() => {
    return calculateRiskLevel(formData.baseRiskValue);
  }, [formData.baseRiskValue]);

  const primaryOptions = useMemo(() => {
    return Object.entries(CATEGORYSTRUCTURE);
  }, []);

  // 优化风险类型变更回调 - 使用函数式更新避免依赖外部状态
  const handleRiskTypeChange = useCallback((typeKey, checked) => {
    setFormData((prev) => {
      if (checked) {
        // 避免重复添加
        if (!prev.riskType.includes(typeKey)) {
          return { ...prev, riskType: [...prev.riskType, typeKey] };
        }
      } else {
        return {
          ...prev,
          riskType: prev.riskType.filter((t) => t !== typeKey),
        };
      }
      return prev;
    });
  }, []);

  return (
    <Card
      className="mb-6 shadow-lg border-purple-200"
      id="emergency-measure-form"
    >
      <CardHeader className="bg-purple-50">
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-purple-600" />
            {riskPoint
              ? `编辑危险点: ${riskPoint.riskName || ""}`
              : "新建危险点"}
          </span>
          <Button variant="ghost" size="icon" onClick={onCancel}>
            <X className="w-4 h-4" />
          </Button>
        </CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 隐藏危险点编码输入框 */}
          {/* 作业分类 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <Label htmlFor="primaryCategory">一级作业类别 *</Label>
              <Select
                value={formData.primaryCategory}
                onValueChange={(value) => {
                  handleFieldChange("primaryCategory", value);
                  handleFieldChange("secondaryCategory", "");
                  handleFieldChange("tertiaryCategory", "");
                }}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择一级分类" />
                </SelectTrigger>
                <SelectContent>
                  {primaryOptions.map(([key, category]) => (
                    <SelectItem key={key} value={key}>
                      {category.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="secondaryCategory">二级作业类别</Label>
              <Select
                value={formData.secondaryCategory}
                onValueChange={(value) => {
                  handleFieldChange("secondaryCategory", value);
                  handleFieldChange("tertiaryCategory", "");
                }}
                disabled={!formData.primaryCategory}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择二级分类" />
                </SelectTrigger>
                <SelectContent>
                  {secondaryOptions.map(([key, category]) => (
                    <SelectItem key={key} value={key}>
                      {category.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label htmlFor="tertiaryCategory">三级作业类别</Label>
              <Select
                value={formData.tertiaryCategory}
                onValueChange={(value) =>
                  handleFieldChange("tertiaryCategory", value)
                }
                disabled={!formData.secondaryCategory}
              >
                <SelectTrigger>
                  <SelectValue placeholder="选择三级分类" />
                </SelectTrigger>
                <SelectContent>
                  {tertiaryOptions.map((tertiary) => (
                    <SelectItem key={tertiary} value={tertiary}>
                      {tertiary}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>

          {/* 风险名称 */}
          <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
            <div>
              <Label htmlFor="riskName">风险名称 *</Label>
              <Input
                id="riskName"
                value={formData.riskName}
                onChange={(e) => handleFieldChange("riskName", e.target.value)}
                placeholder="例如: 基坑边坡坍塌"
                required
              />
            </div>
          </div>

          {/* 风险种类（多选） */}
          <div>
            <Label className="text-sm font-medium text-gray-700 mb-3 block">
              风险种类 * （可多选）
            </Label>
            <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
              {riskTypeS.map((type) => (
                <RiskTypeCheckbox
                  key={type.key}
                  type={type}
                  checked={formData.riskType.includes(type.key)}
                  onCheckChange={(checked) =>
                    handleRiskTypeChange(type.key, checked)
                  }
                />
              ))}
            </div>
            {formData.riskType.length === 0 && (
              <p className="text-red-500 text-xs mt-1">
                请至少选择一种风险种类
              </p>
            )}
          </div>

          {/* 风险描述 */}
          <div>
            <Label htmlFor="riskDescription">危险点描述 *</Label>
            <Textarea
              id="riskDescription"
              value={formData.riskDescription}
              onChange={(e) =>
                handleFieldChange("riskDescription", e.target.value)
              }
              placeholder="详细描述该危险点的具体情况和潜在后果..."
              rows={3}
              required
            />
          </div>

          {/* 适用范围 */}
          <div>
            <Label htmlFor="applicableScope">适用范围</Label>
            <Textarea
              id="applicableScope"
              value={formData.applicableScope}
              onChange={(e) =>
                handleFieldChange("applicableScope", e.target.value)
              }
              placeholder="描述该危险点的适用范围或条件..."
              rows={2}
            />
          </div>

          {/* 风险评估 (LEC法) */}
          <div className="bg-gray-50 p-4 rounded-lg">
            <h4 className="font-semibold mb-4 flex items-center gap-2">
              <AlertTriangle className="w-4 h-4" />
              风险评估 (南方电网LEC法: R = L × C × E)
            </h4>

            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
              {/* 可能性(L) */}
              <div>
                <Label>可能性 (L)</Label>
                <Select
                  value={formData.baseLikelihood.toString()}
                  onValueChange={(value) =>
                    handleFieldChange("baseLikelihood", parseFloat(value))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择可能性值" />
                  </SelectTrigger>
                  <SelectContent>
                    {riskAssessmentSTANDARDS.likelihood.referenceScale.map(
                      (item) => (
                        <SelectItem
                          key={item.value}
                          value={item.value.toString()}
                        >
                          {item.value} - {item.label}
                        </SelectItem>
                      )
                    )}
                  </SelectContent>
                </Select>
              </div>

              {/* 后果(C) */}
              <div>
                <Label>后果 (C)</Label>
                <Select
                  value={formData.baseConsequence.toString()}
                  onValueChange={(value) =>
                    handleFieldChange("baseConsequence", parseFloat(value))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择后果值" />
                  </SelectTrigger>
                  <SelectContent>
                    {riskAssessmentSTANDARDS.consequence.referenceScale.map(
                      (item) => (
                        <SelectItem
                          key={item.value}
                          value={item.value.toString()}
                        >
                          {item.value} - {item.label}
                        </SelectItem>
                      )
                    )}
                  </SelectContent>
                </Select>
              </div>

              {/* 暴露(E) */}
              <div>
                <Label>暴露 (E)</Label>
                <Select
                  value={formData.baseExposure.toString()}
                  onValueChange={(value) =>
                    handleFieldChange("baseExposure", parseFloat(value))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder="选择暴露值" />
                  </SelectTrigger>
                  <SelectContent>
                    {riskAssessmentSTANDARDS.exposure.referenceScale.map(
                      (item) => (
                        <SelectItem
                          key={item.value}
                          value={item.value.toString()}
                        >
                          {item.value} - {item.label}
                        </SelectItem>
                      )
                    )}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 计算结果 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 bg-white rounded-lg border">
              <div>
                <Label className="text-sm text-gray-600">计算风险值</Label>
                <div className="text-2xl font-bold text-gray-800">
                  R = {formData.baseLikelihood} × {formData.baseConsequence} ×{" "}
                  {formData.baseExposure} = {formData.baseRiskValue.toFixed(1)}
                </div>
              </div>
              <div>
                <Label className="text-sm text-gray-600">风险等级</Label>
                <div className="mt-1">
                  <Badge
                    style={{
                      backgroundColor: currentRiskLevel.color,
                      color: "white",
                    }}
                    className="text-sm px-3 py-1"
                  >
                    {currentRiskLevel.name}
                  </Badge>
                  <p className="text-xs text-gray-600 mt-1">
                    {currentRiskLevel.description}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* 控制措施 */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <Label>控制措施</Label>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={addMeasure}
              >
                <Plus className="w-4 h-4 mr-2" />
                添加措施
              </Button>
            </div>
            <div className="space-y-2">
              {formData.controlMeasures.map((measure, index) => (
                <ControlMeasureInput
                  key={index}
                  measure={measure}
                  index={index}
                  onMeasureChange={handleMeasureChange}
                  onRemove={removeMeasure}
                  canRemove={formData.controlMeasures.length > 1}
                />
              ))}
            </div>
          </div>

          {/* 提交按钮 */}
          <div className="flex justify-end gap-3 pt-4 border-t">
            <Button type="button" variant="outline" onClick={onCancel}>
              <X className="w-4 h-4 mr-2" />
              取消
            </Button>
            <Button type="submit" className="bg-purple-600 hover:bg-purple-700">
              <Save className="w-4 h-4 mr-2" />
              {riskPoint ? "更新危险点" : "创建危险点"}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
});
